package org.looop.chuck.parser.impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.looop.chuck.domain.AppInfo;
import org.looop.chuck.persistence.PersistenceManager;
import org.looop.chuck.task.URLTaskManager;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class HiApkListHTMLParser extends AppInfoListHTMLParser {
	private String url;
	private static Pattern onclickPattern = Pattern.compile("ChangeHash\\((\\d+),true\\);");
	private static Pattern urlPattern = Pattern.compile("http://apk\\.hiapk\\.com/(App|Game)\\.aspx\\?action=(FindAppSoftList|FindGameSoftList)\\&categoryId=(\\d+)\\&currentHash=(\\d+)_(\\d+)_(\\d+)_(\\d+)_(\\d+)_(\\d+)_(\\d+)");
	private static String urlFormat = "http://apk.hiapk.com/{0}.aspx?action={1}&categoryId={2}&currentHash={3}_{4}_{5}_{6}_{7}_{8}_{9}";
	public HiApkListHTMLParser(PersistenceManager persistenceManager,
			URLTaskManager urlTaskManager, String url) {
		super(persistenceManager, urlTaskManager);
		this.url = url;
	}

	@Override
	protected List<AppInfo> extraAppInfoList(Element rawDoc) {
		return Collections.emptyList();
	}

	@Override
	protected List<String> gernerateNewTask(Element rawDoc) {
		List<String> taskList = new ArrayList<String>();
		addListTask(rawDoc, taskList);
		addDetailTask(rawDoc, taskList);
		return taskList;
	}

	private void addDetailTask(Element rawDoc, List<String> taskList) {
		List<Element> spanList = getElementByTagNameAndAttribute(rawDoc, "span", "class", "font14 list_title");
		if(spanList != null && spanList.size() > 0){
			for (Element span : spanList) {
				Node aNode = span.getFirstChild();
				if(aNode != null && aNode instanceof Element){
					String detailUrl = ((Element)aNode).getAttribute("href");
					if(StringUtils.isNotBlank(detailUrl)){
						taskList.add(detailUrl);
					}
				}
			}
		}
	}

	private void addListTask(Element rawDoc, List<String> taskList) {
		NodeList nodeList = rawDoc.getElementsByTagName("span");
		if(nodeList != null && nodeList.getLength() > 0){
			for(int i=0; i < nodeList.getLength(); i++){
				Node node = nodeList.item(i);
				if(!(node instanceof Element)){
					continue;
				}
				Element elementNode = (Element)node;
				if(StringUtils.equals(elementNode.getAttribute("class"), "pagespan pagespanable")){
					String onclick = elementNode.getAttribute("onclick");
					if(StringUtils.isNotBlank(onclick)){
						Matcher onclickMatcher = onclickPattern.matcher(onclick);
						if(onclickMatcher.find() && onclickMatcher.groupCount() > 0){
							String pageNum = onclickMatcher.group(1);
							Matcher urlMatcher = urlPattern.matcher(url);
							if(urlMatcher.find() && urlMatcher.groupCount() == 10){
								if(!urlMatcher.group(2).equalsIgnoreCase(pageNum)){
									String taskUrl = MessageFormat.format(urlFormat, new Object[]{urlMatcher.group(1), urlMatcher.group(2), urlMatcher.group(3), pageNum, urlMatcher.group(5), urlMatcher.group(6), urlMatcher.group(7), urlMatcher.group(8), urlMatcher.group(9), urlMatcher.group(10)});
									taskList.add(taskUrl);
								}
							}
						}
					}
				}
			}
		}
	}
	
	public static boolean matches(String url){
		return urlPattern.matcher(url).find();
	}
	
	public static void main(String[] args) {
//		String value = "http://apk.hiapk.com/App.aspx?action=FindAppSoftList&categoryId=45&currentHash=213_1_0_0_0_0_0";
		String value = "http://apk.hiapk.com/Game.aspx?action=FindGameSoftList&categoryId=31&currentHash=1_1_0_0_0_0_0";
		String pageNum = "50";
		Matcher urlMatcher = urlPattern.matcher(value);
		if(urlMatcher.find()){
			System.out.println(MessageFormat.format(urlFormat, new Object[]{urlMatcher.group(1), urlMatcher.group(2), urlMatcher.group(3), pageNum, urlMatcher.group(5), urlMatcher.group(6), urlMatcher.group(7), urlMatcher.group(8), urlMatcher.group(9), urlMatcher.group(10)}));
			System.out.println(urlMatcher.groupCount());
			
		}else{
			System.out.println("Not Found");
		}
	}

}
